package com.mingqijia.gassafety.webserver.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gap.basic.exception.BizException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.mapper.ConsumerMapper;
import com.mingqijia.gassafety.db.mapper.InformRecordMapper;
import com.mingqijia.gassafety.db.mapper.RunningStrategyExtMapper;
import com.mingqijia.gassafety.db.mapper.RunningStrategyMapper;
import com.mingqijia.gassafety.shared.constant.*;
import com.mingqijia.gassafety.shared.dto.LogVO;
import com.mingqijia.gassafety.shared.dto.TaskDetailParamDTO;
import com.mingqijia.gassafety.shared.dto.TaskDetailRespDTO;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageColumns;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.shared.utils.message.SendMessageService;
import com.mingqijia.gassafety.webserver.request.*;
import com.mingqijia.gassafety.webserver.response.RunningStrategyDetailRes;
import com.mingqijia.gassafety.webserver.response.RunningStrategyRes;
import com.mingqijia.gassafety.webserver.response.WarnStrategyRes;
import com.mingqijia.gassafety.webserver.service.*;
import com.mingqijia.gassafety.webserver.utils.LogRecordAspect;
import com.mingqijia.gassafety.webserver.utils.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.*;
import java.util.stream.Collectors;

import static com.mingqijia.gassafety.shared.constant.Constants.ORG_MAP_SUBSCODE;

/**
 * <p>
 * 运行策略 服务实现类
 * </p>
 *
 * @author fei.zhang
 * @since 2023-12-13
 */
@Service
@Slf4j
public class RunningServiceImpl extends ServiceImpl<RunningStrategyMapper, RunningStrategy> implements RunningStrategyService {

    @Autowired
    private RunningStrategyMapper runningStrategyMapper;

    @Autowired
    private RunningStrategyExtMapper extMapper;
    public static final String format = "yyyy-MM-dd HH:mm:ss";
    public static final String split = ";";
    @Autowired
    EquipmentServiceImpl equipmentService;
    @Autowired
    ConsumerMapper consumerMapper;

    @Autowired
    InformRecordMapper informRecordMapper;

    @Autowired
    FieldTemplateService fieldTemplateService;

    @Autowired
    private ServicePkgRecordService servicePkgRecordService;

    @Autowired
    SendMessageService sendMessageService;

    @Resource
    CompanyService companyService;


    @Autowired
    ConfigureHolder holder;

    /**
     * 存储策略
     * @param request
     * @param source
     * @return
     */
    @Override
    public void saveWarnStrategy(SaveRunningStrategyRequest request, int source) {
        List<RunningStrategyExtRequest> extDatas = request.getExtData();
        if (!CollectionUtils.isEmpty(extDatas)){
            String str="";
            for (RunningStrategyExtRequest extData : extDatas) {
                //前端传错进行转换
                if (extData.getPushType()==1){
                    extData.setPushType(2);
                    str=str+extData.getPushType()+split;
                    continue;
                }
                if (extData.getPushType()==2)extData.setPushType(1);
                str=str+extData.getPushType()+split;
            }
            request.setAdviceType(str);
        }
        String spId = ApplicationUtils.getWorkingSpId();
        RunningStrategy warn = new RunningStrategy();
        if (request.getStrategyObj() != 0 &&
                !StringUtils.isEmpty(request.getStrategyObjValues()) && source != 1) {
            warn.setStrategyObjValues(request.getStrategyObjValues() + split);
            request.setStrategyObjValues(request.getStrategyObjValues() + split);
        }
        List<RunningStrategy> warnStrategies = queryStrategy(request, spId, null, request.getStrategyType());
        log.info("running-warnStrategies:{}", JSON.toJSONString(warnStrategies));
        List<RunningStrategy> checkStrategies = runningStrategyMapper.checkStrategies(spId, request.getStrategyType());
        log.info("running-checkStrategies:{}", JSON.toJSONString(checkStrategies));
        if (!CollectionUtil.isEmpty(warnStrategies) || (request.getStrategyObj() == 0
                && !CollectionUtil.isEmpty(checkStrategies)))
            throw new BizException("当前客户已绑定该规则类型");
            checkRule(request);

            BeanUtils.copyProperties(request, warn);
            warn.setSpId(spId);
            warn.setIsDisabled(request.getSaveAndEnable());
            warn.setAdviceType(request.getAdviceType());
            log.info("running-warn:{}", com.alibaba.fastjson.JSONObject.toJSONString(warn));
            runningStrategyMapper.insert(warn);
            if (!CollectionUtils.isEmpty(extDatas)){
                saveBatchExts(extDatas, warn, spId);
            }
        //企业级操作日志
        LogVO vo = new LogVO();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("【规则名称：" + request.getRuleName() + "】成功");
        vo.setDetail(stringBuilder.toString());
        vo.setStrategyType(StrategyTypeEnum.matcher(request.getStrategyType()).getMsg());
        LogRecordAspect.threadLocal.set(vo);
    }

    private void checkRule(SaveRunningStrategyRequest request) {
        List<RunningStrategyExtRequest> extData = request.getExtData();
        if (!CollectionUtils.isEmpty(extData)){
            for (RunningStrategyExtRequest extDatum : extData) {
                if (request.getStrategyType()!=2&&request.getStrategyType()!=3&&(extDatum.getPushNumber()==null||extDatum.getPushNumber()<=0))
                    throw new BizException("推送次数为1-200以内的正整数");
                if(request.getStrategyType()==2){
                    extDatum.setPushFrequency(3);
                    extDatum.setPushNumber(1);
                }
                if(extDatum.getPushNumber() == null) {
                    extDatum.setPushNumber(1);
                }
            }
        }
    }
    /**
     * 编辑策略
     *
     * @param request
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editWarnStrategy(SaveRunningStrategyRequest request, int source) {
        List<RunningStrategyExtRequest> extDatas = request.getExtData();
        if (!CollectionUtils.isEmpty(extDatas)){
            String str="";
            for (RunningStrategyExtRequest extData : extDatas) {
                //前端传错进行转换
                if (extData.getPushType()==1){
                    extData.setPushType(2);
                    str=str+extData.getPushType()+split;
                    continue;
                }
                if (extData.getPushType()==2)extData.setPushType(1);
                str=str+extData.getPushType()+split;
            }
            request.setAdviceType(str);
        }
        String spId = ApplicationUtils.getWorkingSpId();
        if (request.getId() == null) throw new BizException("id必传字段");
        RunningStrategy warn = runningStrategyMapper.selectWarnStrategyById(request.getId());
        log.info("running-warn:{}", com.alibaba.fastjson.JSONObject.toJSONString(warn));
        if (warn == null) throw new BizException("数据不存在或已失效");
        if (warn.getIsDisabled() == 0) {
            if (informRecordMapper.selectWarnStrategyUse(request.getId()) > 0)
                throw new BizException("执行中的策略不可编辑");
        }
        if (request.getStrategyObj() != 0 &&
                !StringUtils.isEmpty(request.getStrategyObjValues()) && source != 1) {
            request.setStrategyObjValues(request.getStrategyObjValues() + split);
        }
        List<RunningStrategy> warnStrategies = queryStrategy(request, spId, request.getId(), request.getStrategyType());
        log.info("running-warnStrategies:{}", com.alibaba.fastjson.JSONObject.toJSONString(warnStrategies));
        if (!CollectionUtil.isEmpty(warnStrategies))
            throw new BizException("客户已绑定该规则类型");
        List<RunningStrategyExtRequest> extData = request.getExtData();
        checkRule(request);
            RunningStrategy warnStrategy = new RunningStrategy();
            BeanUtils.copyProperties(request, warnStrategy);
            warnStrategy.setSpId(spId);
            warnStrategy.setIsDisabled(request.getSaveAndEnable());
            if (StringUtils.isEmpty(request.getStrategyObjValues())) {
                warnStrategy.setStrategyObjValues("");
            }
        LambdaQueryWrapper<RunningStrategyExt> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.or().eq(RunningStrategyExt::getStrategyId,warn.getId())
                .eq(RunningStrategyExt::getIsDeleted,0)
                .orderByAsc(RunningStrategyExt::getPushServiceExpireLevel);
        List<RunningStrategyExt> runningStrategyExts = extMapper.selectList(queryWrapper);
        warnStrategy.setAdviceType(request.getAdviceType());
        log.info("running-warnStrategy:{}", com.alibaba.fastjson.JSONObject.toJSONString(warnStrategy));
            runningStrategyMapper.updateById(warnStrategy);
            //更新数据
            extMapper.updateByStrategyid(request.getId());
            saveBatchExts(extData, warnStrategy, spId);
            //企业级操作日志
            LogVO vo = new LogVO();
            StringBuilder stringBuilder = new StringBuilder();
            String detail = LogUtil.compareEntity(warnStrategy, warn, RunningStrategy.class);
            log.info("LogVO-detail:{}", detail);
            if (detail.contains("对象：由【")) {
                String replace = detail.replace("【", "")
                        .replace("】", "").replace("对象：由", ";")
                        .replace("变更为", "").replace("】", "】\n").trim();
                String[] split = replace.split(";");
                log.info("LogVO-split:{}", com.alibaba.fastjson.JSONObject.toJSONString(split));
                if (warnStrategy.getStrategyObj() == 3) {
                    if (split.length > 0) {
                        String[] splitNew = warnStrategy.getStrategyObjValues().split(";");
                        String[] splitOld = warn.getStrategyObjValues().split(";");
                        LambdaQueryWrapper<ServicePkgRecord> recordLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        recordLambdaQueryWrapper.in(ServicePkgRecord::getId, split)
                                .eq(ServicePkgRecord::getSpId, spId)
                                .eq(ServicePkgRecord::getIsDeleted, 0);
                        List<ServicePkgRecord> pkgRecords = servicePkgRecordService.list(recordLambdaQueryWrapper);
                        log.info("LogVO-pkgRecords:{}", pkgRecords);
                        if (CollectionUtil.isNotEmpty(pkgRecords)) {
                            Map<Integer, String> servicePkgMap = pkgRecords.stream().collect(Collectors.toMap(ServicePkgRecord::getId, ServicePkgRecord::getPgkName, (a1, a2) -> a1));
                            StringBuilder sbOld = new StringBuilder();
                            for (String s : splitOld) {
                                if (!StringUtils.isEmpty(s) && servicePkgMap.containsKey(Integer.valueOf(s))) {
                                    sbOld.append(servicePkgMap.get(Integer.valueOf(s))).append(";");
                                }
                            }
                            if (sbOld.length() > 0) {
                                detail = detail.replace("对象：由【" + warn.getStrategyObjValues(), "对象：由【" +sbOld.toString());
                            }
                            StringBuilder sbNew = new StringBuilder();
                            for (String s : splitNew) {
                                if (!StringUtils.isEmpty(s) && servicePkgMap.containsKey(Integer.valueOf(s))) {
                                    sbNew.append(servicePkgMap.get(Integer.valueOf(s))).append(";");
                                }
                            }
                            if (sbNew.length() > 0) {
                                detail = detail.replace(warnStrategy.getStrategyObjValues(), sbNew.toString());
                            }
                        }
                    }
                } else {
                    List<Map<String, String>> industryType = equipmentService
                            .dictMap("Industry_type", null, spId);
                    log.info("LogVO-industryType:{}", industryType);
                    if (CollectionUtil.isNotEmpty(industryType) && split.length > 0) {
                        for (String s : split) {
                            boolean flag=false;
                            for (Map<String, String> map : industryType) {
                                if (map.get("value").equals(s)) {
                                    detail = detail.replace(s, map.get("alias"));
                                    log.info("detail:{}", detail);
                                    flag=true;
                                }
                            }
                            log.info("LogVO-flag:{},s:{}",flag,s);
                            if (!flag){
                                String name = consumerMapper.selectName(s);
                                log.info("LogVO-name:{}",name);
                                if (name!=null) {
                                    detail = detail.replace(s, name);
                                }
                                log.info("flag-detail:{}", detail);
                            }
                        }
                    }
                }

            }
            if (detail.length() > 0) {
                detail = detail + "\n";
            }
            Map<Integer, List<RunningStrategyExtRequest>> collect = extData.stream().
                    collect(Collectors.groupingBy(RunningStrategyExtRequest::getPushType, Collectors.toList()));
            Map<Integer, List<RunningStrategyExt>> old = runningStrategyExts.stream().
                collect(Collectors.groupingBy(RunningStrategyExt::getPushType, Collectors.toList()));
            detail = detail + getLogRecord("机器人外呼:", warn.getStrategyType(), old.get(3), request.getStrategyType(),collect.get(3));
            detail = detail + getLogRecord("短信消息:", warn.getStrategyType(), old.get(1), request.getStrategyType(),collect.get(1));
            detail = detail + getLogRecord("微信模版消息:", warn.getStrategyType(),  old.get(2), request.getStrategyType(),collect.get(2));
            if (request.getStrategyType()==2) detail=detail+"推送时间：由【"+DtuPushTypeEnum.getPushTypes(runningStrategyExts.get(0).getPushTime()).getName()+"】" +
                    "变更成【"+DtuPushTypeEnum.getPushTypes(extData.get(0).getPushTime()).getName()+"】";
            stringBuilder.append(detail);
            vo.setDetail(stringBuilder.toString());
            vo.setStrategyType(StrategyTypeEnum.matcher(warnStrategy.getStrategyType()).getMsg());
            log.info("LogVO-vo:{}", com.alibaba.fastjson.JSONObject.toJSONString(vo));
            LogRecordAspect.threadLocal.set(vo);
    }

    /**
     *
     * @param prefix 前缀
     * @param oldStrategyType 原策略类型
     * @param oldList 原策略列表
     * @param newStrategyType 新策略类型
     * @param newList 新策略列表
     * @return
     */
    private String getLogRecord(String prefix, Integer oldStrategyType, List<RunningStrategyExt> oldList, Integer newStrategyType, List<RunningStrategyExtRequest> newList) {
        StringBuilder left = new StringBuilder();
        StringBuilder right = new StringBuilder();
        try {
            // 该项无变更
            if (CollectionUtils.isEmpty(oldList) && CollectionUtils.isEmpty(newList)) {
                return "";
            }
            // 原来为空
            if (CollectionUtils.isEmpty(oldList)) {
                left.append("由【关闭】");
            } else if (oldStrategyType == StrategyTypeEnum.DEVICE_BROKEN.getCode()
                || oldStrategyType == StrategyTypeEnum.DEVICE_OFFLINE.getCode()){
                left.append("由【开启，");
                if (!StringUtils.isEmpty(oldList.get(0).getPushLevel())) {
                    left.append("推送给客户联系人级别").append(oldList.get(0).getPushLevel()).append("，");
                }
                left.append("发送间隔").append(FrequencyTypeEnum.getPushTypes(oldList.get(0).getPushFrequency()).getName())
                    .append("，推送次数：").append(oldList.get(0).getPushNumber()).append("，推送时间：").append(DtuPushTypeEnum.getPushTypes(oldList.get(0).getPushTime()).getName()).append("】");
            } else if (oldStrategyType == StrategyTypeEnum.DEVICE_RUNNING.getCode()){
                left.append("由【开启");
                if (!StringUtils.isEmpty(oldList.get(0).getPushLevel())) {
                    left.append("，推送给客户联系人级别").append(oldList.get(0).getPushLevel());
                }
                left.append("】");
            } else if (oldStrategyType == StrategyTypeEnum.DEVICE_EXPIRATION.getCode()){
                left.append("由【开启，");
                if (!StringUtils.isEmpty(oldList.get(0).getPushLevel())) {
                    left.append("推送给客户联系人级别").append(oldList.get(0).getPushLevel()).append("，");
                }
                if (!StringUtils.isEmpty(oldList.get(0).getPushPhones())) {
                    left.append("推送给额外推送手机号码：").append(oldList.get(0).getPushPhones()).append("，");
                }
                for (RunningStrategyExt ext : oldList) {
                    left.append(PushServicePeriodLevelEnum.getPushServicePeriodLevel(ext.getPushServiceExpireLevel()).getName()).append("，")
                        .append("发送间隔").append(ext.getPushServiceExpireLevel() == PushServicePeriodLevelEnum.PERIOD.getCode() ? ext.getPushFrequency() + "小时" : FrequencyTypeEnum.getPushTypes(ext.getPushFrequency()).getName());
                    if (ext.getPushServiceExpireLevel() != PushServicePeriodLevelEnum.UNEXPIRED.getCode()) {
                        left.append("，推送次数：").append(ext.getPushNumber());
                    }
                    left.append("，推送时间：").append(DtuPushTypeEnum.getPushTypes(ext.getPushTime()).getName()).append("；");
                }
                left.deleteCharAt(left.length()-1);
                left.append("】");
            }
            // 现在为空
            if (CollectionUtils.isEmpty(newList)) {
                right.append("【关闭】\n");
            } else if (newStrategyType == StrategyTypeEnum.DEVICE_BROKEN.getCode()
                    || newStrategyType == StrategyTypeEnum.DEVICE_OFFLINE.getCode()){
                right.append("【开启，");
                if (!StringUtils.isEmpty(newList.get(0).getPushLevel())) {
                    right.append("推送给客户联系人级别").append(newList.get(0).getPushLevel()).append("，");
                }
                right.append("发送间隔").append(FrequencyTypeEnum.getPushTypes(newList.get(0).getPushFrequency()).getName())
                        .append("，推送次数：").append(newList.get(0).getPushNumber()).append("，推送时间：").append(DtuPushTypeEnum.getPushTypes(newList.get(0).getPushTime()).getName()).append("】\n");
            } else if (newStrategyType == StrategyTypeEnum.DEVICE_RUNNING.getCode()){
                right.append("【开启");
                if (!StringUtils.isEmpty(newList.get(0).getPushLevel())) {
                    right.append("，推送给客户联系人级别").append(newList.get(0).getPushLevel());
                }
                right.append("】\n");
            } else if (newStrategyType == StrategyTypeEnum.DEVICE_EXPIRATION.getCode()){
                right.append("【开启，");
                if (!StringUtils.isEmpty(newList.get(0).getPushLevel())) {
                    right.append("推送给客户联系人级别").append(newList.get(0).getPushLevel()).append("，");
                }
                if (!StringUtils.isEmpty(newList.get(0).getPushPhones())) {
                    right.append("推送给额外推送手机号码：").append(newList.get(0).getPushPhones()).append("，");
                }
                for (RunningStrategyExtRequest ext : newList) {
                    right.append(PushServicePeriodLevelEnum.getPushServicePeriodLevel(ext.getPushServiceExpireLevel()).getName()).append("，")
                        .append("发送间隔").append(ext.getPushType() == MessagePushTypeEnum.WX.getCode() ? ext.getPushFrequency() + "小时" : FrequencyTypeEnum.getPushTypes(ext.getPushFrequency()).getName());
                    if (ext.getPushServiceExpireLevel() != PushServicePeriodLevelEnum.UNEXPIRED.getCode()) {
                        right.append("，推送次数：").append(ext.getPushNumber());
                    }
                    right.append("，推送时间：").append(DtuPushTypeEnum.getPushTypes(ext.getPushTime()).getName()).append("；");
                }
                right.deleteCharAt(right.length()-1);
                right.append("】\n");
            }


        } catch (Exception e) {
            log.error("getLogRecord-error:{}",e);
        }
        return new StringBuilder().append(prefix).append(left)
                .append("变更成").append(right).toString();
    }


    @Override
    public PageUtil<RunningStrategyRes> warnStrategyList(RunningStrategyRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        int templateType = fieldTemplateService.getBySpId(spId);
        request.setTemplateType(templateType);
        log.info("warnStrategyList-templateType:{}", com.alibaba.fastjson.
                JSONObject.toJSONString(request));
        Page<RunningStrategy> page = PageHelper.startPage(request.getPage(), request.getPageSize());
        RunningStrategy warnStrategy = new RunningStrategy();
        BeanUtils.copyProperties(request, warnStrategy);
        warnStrategy.setSpId(spId);
        if (request.getCreatedAt() != null) {
            String createdAt = request.getCreatedAt();
            String[] split = createdAt.split(" ");
            if (split.length==2){
                DateTime parse = DateUtil.parse(split[0], "yyyy-MM-dd");
                DateTime end = DateUtil.parse(split[0]+" 23:59:59", "yyyy-MM-dd HH:mm:ss");
                warnStrategy.setCreatedAt(parse);
                warnStrategy.setCreatedAtEnd(end);
            }
        }
        List<String> splits = new ArrayList<>();
        if (request.getStrategyObj() != null) {
            warnStrategy.setStrategyObj(Integer.parseInt(request.getStrategyObj()));
            String objValues = request.getStrategyObjValues();
            if (!StringUtils.isEmpty(objValues)
                    && objValues.contains(split)) {
                splits = new ArrayList<>(Arrays.asList(objValues.split(WarnStrategyServiceImpl.split)));

            } else if (!StringUtils.isEmpty(objValues)) {
                splits.add(objValues);
            }
        }

        List<RunningStrategy> warnStrategies = runningStrategyMapper.selectListByCondition(warnStrategy, splits);
        log.info("running-warnStrategies:{}",warnStrategies);
        List<RunningStrategyRes> warnStrategyResList = new ArrayList<>();
        for (RunningStrategy strategy : warnStrategies) {
            String objValues = strategy.getStrategyObjValues();
            if (!"0".equals(request.getStrategyObj()) && !StringUtils.isEmpty(request.getStrategyObjValues())
                    && request.getStrategyObjValues().contains(split)) {
                //行业和客户选择的情况下
                int i = 0;
                String[] split = objValues.split(WarnStrategyServiceImpl.split);
                for (String objValue : splits) {
                    if (new ArrayList<>(Arrays.asList(split)).contains(objValue)) {
                        i = 1;
                        continue;
                    }
                }
                if (i == 0) {
                    continue;
                }
            }
            RunningStrategyRes warnStrategyRes = new RunningStrategyRes();
            BeanUtils.copyProperties(strategy, warnStrategyRes);
            warnStrategyRes.setStrategyType(StrategyTypeEnum.matcher(strategy.getStrategyType()).getMsg());
            if (strategy.getCreatedAt() != null)
                warnStrategyRes.setCreatedAt(DateUtil.format(strategy.getCreatedAt(), format));
            if (strategy.getUpdatedAt() != null)
                warnStrategyRes.setUpdatedAt(DateUtil.format(strategy.getUpdatedAt(), format));
            warnStrategyResList.add(warnStrategyRes);
        }

        //进行转换
        getComsumerIndustryName(spId, warnStrategyResList, request.getTemplateType());
        //区分模板
        List<PageColumns> add = new ArrayList<>();
        if (TemplateTypeEnum.TEMPLATE_TYPE_2.getCode() == request.getTemplateType()) {
            add = PageColumnConst.add(PageColumnConst.RunningStrategyTitles, PageColumnConst.RunningStrategyIndices);
        } else {
            add = PageColumnConst.add(PageColumnConst.RunningStrategyTitles, PageColumnConst.RunningStrategyIndices);
        }
        PageUtil pageInfo = new PageUtil<>(request.getPage(),
                request.getPageSize(), page.getTotal(), warnStrategyResList, add);

        return pageInfo;
    }

    @Override
    public RunningStrategyDetailRes getStrategyDetail(Long id) {
        RunningStrategyDetailRes res = new RunningStrategyDetailRes();
        RunningStrategy strategy = this.getById(id);
        if (strategy == null){
           throw  new BizException("数据不存在");
        }
        BeanUtils.copyProperties(strategy, res);
//        if (res.getStrategyObj() == 2) {
//            String[] consumerList = res.getStrategyObjValues().split(",");
//            LambdaQueryWrapper<Consumer> lqw = new LambdaQueryWrapper<>();
//            lqw.in(Consumer::getId, consumerList).eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE);
//            List<Consumer> consumers = consumerMapper.selectList(lqw);
//            StringBuilder sb = new StringBuilder();
//            if (!CollectionUtils.isEmpty(consumers)) {
//                for (Consumer consumer : consumers) {
//                    sb.append(consumer.getName()).append(",");
//                }
//            }
//            res.setStrategyObjName(sb.toString().substring(0, sb.toString().length() - 1));
//        }
        //查询微信消息模板内容
        //批量查询字典
        List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
        String orgCode;
        if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
            orgCode = orgMapSubsCodeList.get(0).getValue();
        } else {
            orgCode = companyService.getOrgCode(strategy.getSpId(), null);
        }
        //查询微信消息模板内容
        if (StringUtils.isEmpty(strategy.getWxMsgCode())) {
            TaskDetailParamDTO smsTaskDetailParam = new TaskDetailParamDTO();
            smsTaskDetailParam.setSpId(strategy.getSpId());
            smsTaskDetailParam.setOrgCode(orgCode);
            smsTaskDetailParam.setCode(strategy.getWxMsgCode());
            TaskDetailRespDTO smsTaskDetailResp = sendMessageService.getMsgTemplateContent(smsTaskDetailParam);
            String smsWXContent = smsTaskDetailResp.getTemplateContent();
            res.setWxMsgCodeContent(smsWXContent);
        }

        //查询短信消息模板内容
        if (StringUtils.isEmpty(strategy.getSmsMsgCode())) {
            TaskDetailParamDTO smsTaskDetailParam = new TaskDetailParamDTO();
            smsTaskDetailParam.setSpId(strategy.getSpId());
            smsTaskDetailParam.setOrgCode(orgCode);
            smsTaskDetailParam.setCode(strategy.getSmsMsgCode());
            TaskDetailRespDTO smsTaskDetailResp = sendMessageService.getMsgTemplateContent(smsTaskDetailParam);
            String smsSmsContent = smsTaskDetailResp.getTemplateContent();
            res.setSmsMsgCodeContent(smsSmsContent);
        }
        LambdaQueryWrapper<RunningStrategyExt> lqw = new LambdaQueryWrapper<>();
        lqw.eq(RunningStrategyExt::getStrategyId, id).eq(RunningStrategyExt::getIsDeleted, Constants.IS_DELETED_FALSE);
        List<RunningStrategyExt> exts = extMapper.selectList(lqw);
        List<RunningStrategyExtRequest> extDatas = new ArrayList<>();
        if (!CollectionUtils.isEmpty(exts)){
            for (RunningStrategyExt ext : exts) {
                //前端传错进行转换
                if (ext.getPushType()==1){
                    ext.setPushType(2);
                } else if (ext.getPushType()==2){
                    ext.setPushType(1);
                }
                RunningStrategyExtRequest extData = new RunningStrategyExtRequest();
                BeanUtils.copyProperties(ext, extData);
                extDatas.add(extData);
            }
        }
        res.setExtData(extDatas);
        return res;
    }

    @Override
    public void activeStrategy(UpdateRunningStrategyRequest request) {
        LambdaUpdateWrapper<RunningStrategy> lqw = new LambdaUpdateWrapper<>();
        lqw.in(RunningStrategy::getId, request.getIds()).set(RunningStrategy::getIsDisabled, request.getDisable());
        this.update(lqw);
        //企业级操作日志
        LogVO vo = new LogVO();
        List<RunningStrategy> strategyList = this.list(lqw);
        String detail = "【规则名称：" + strategyList.stream().map(RunningStrategy::getRuleName).collect(Collectors.joining("\n")) + "】";
        String commomInfo =  strategyList.stream().map(RunningStrategy::getRuleName).collect(Collectors.joining("\n")) ;
        String strategyType = strategyList.stream().map(item -> {
            return StrategyTypeEnum.matcher(item.getStrategyType()).getMsg();
        }).distinct().collect(Collectors.joining("\n"));
        if (strategyList.size() > 1 ){
            if (request.getDisable() == 1) {
                vo.setOperateRecordEnum(OperateRecordEnum.OPERATE_TYPE_52);
            } else {
                vo.setOperateRecordEnum(OperateRecordEnum.OPERATE_TYPE_53);
            }
        }else if (request.getDisable() == 0){
            vo.setOperateRecordEnum(OperateRecordEnum.OPERATE_TYPE_51);
        }
        vo.setDetail(detail);
        vo.setCommonInfo(commomInfo);
        vo.setStrategyType(strategyType);
        LogRecordAspect.threadLocal.set(vo);
    }

    @Override
    public void deleteStrategy(UpdateRunningStrategyRequest request) {
        LambdaUpdateWrapper<RunningStrategy> lqw = new LambdaUpdateWrapper<>();
        lqw.in(RunningStrategy::getId, request.getIds()).set(RunningStrategy::getIsDeleted, Constants.IS_DELETED_TRUE);
        this.update(lqw);
        //企业级操作日志
        LogVO vo = new LogVO();
        List<RunningStrategy> strategyList = this.list(lqw);
        String detail = "【规则名称：" + strategyList.get(0).getRuleName() + "】";
        String commomInfo =  strategyList.get(0).getRuleName() ;
        String strategyType = StrategyTypeEnum.matcher(strategyList.get(0).getStrategyType()).getMsg();
        vo.setDetail(detail);
        vo.setCommonInfo(commomInfo);
        vo.setStrategyType(strategyType);
        LogRecordAspect.threadLocal.set(vo);
    }

    public List<RunningStrategy> queryStrategy(SaveRunningStrategyRequest request, String spId, Long id,Integer strategyType) {
        String strategyObjValues = request.getStrategyObjValues();
        if (request.getStrategyObj() != 0 && StringUtils.isEmpty(strategyObjValues))
            throw new BizException("客户id或者行业id不能为空");
        String[] array = new String[1];

        if (!StringUtils.isEmpty(strategyObjValues) && strategyObjValues.contains(split)) {
            array = strategyObjValues.split(WarnStrategyServiceImpl.split);

        } else if (!StringUtils.isEmpty(strategyObjValues)) {
            array[0] = strategyObjValues;
        } else if (StringUtils.isEmpty(strategyObjValues)) {
            array = null;
        }
        List<RunningStrategy> warnStrategies = runningStrategyMapper
                .selectByIdStrategyObjValues(spId, array, request.getStrategyObj(), id,strategyType);
        if (!CollectionUtil.isEmpty(warnStrategies) && array != null) {
            Set<RunningStrategy> res = new HashSet<>();
            String[] finalArray = array;
            warnStrategies.forEach(warnStrategy -> {
                if (!StringUtils.isEmpty(warnStrategy.getStrategyObjValues())) {
                    String[] split = warnStrategy.getStrategyObjValues()
                            .split(WarnStrategyServiceImpl.split);
                    List<String> list = new ArrayList<>(Arrays.asList(split));
                    for (String s : finalArray) {
                        if (list.contains(s)) {
                            res.add(warnStrategy);
                            break;
                        }
                    }
                }
            });
            if (CollectionUtil.isEmpty(res)) {
                return new ArrayList<>();
            }
        }
        return warnStrategies;
    }

    private void saveBatchExts(List<RunningStrategyExtRequest> extData, RunningStrategy warnStrategy, String spId) {
        List<RunningStrategyExt> exts = new ArrayList<>();
        //log.info("入参的集合为:{}", extData);
        if (!CollectionUtil.isEmpty(extData)) {
            for (int i = 0; i < extData.size(); i++) {
                RunningStrategyExtRequest warnStrategyExtRequest = extData.get(i);
                if (!StringUtils.isEmpty(warnStrategyExtRequest.getPushPhones())){
                    String pushPhones = warnStrategyExtRequest.getPushPhones().replace("；",";");
                    warnStrategyExtRequest.setPushPhones(pushPhones);
                }
                RunningStrategyExt warnStrategyExt = new RunningStrategyExt();
                BeanUtils.copyProperties(warnStrategyExtRequest, warnStrategyExt);
                warnStrategyExt.setStrategyId(warnStrategy.getId());
                warnStrategyExt.setSpId(spId);
                warnStrategyExt.setSort(i);
                exts.add(warnStrategyExt);
            }
            //log.info("新增的集合为:{}", exts);
            extMapper.insertBatch(exts);
        }
    }

    public void getComsumerIndustryName(String spId, List<RunningStrategyRes> warnList, Integer templateType) {
        log.info("getComsumerIndustryName-params:{},{},{},", spId,
                com.alibaba.fastjson.JSONObject.toJSONString(warnList),
                templateType);
        //按照行业选择
        List<Map<String, String>> industryType = equipmentService
                .dictMap("Industry_type", null, spId);
        //客户id
        List<Integer> consumerIds = new ArrayList<>();
        //服务套餐id
        List<Integer> pkgIds = new ArrayList<>();
        for (RunningStrategyRes strategyRes : warnList) {
            String[] r = strategyRes.getStrategyObjValues().split(WarnStrategyServiceImpl.split);
            if (strategyRes.getStrategyObj() == 2) {
                for (String consumerId : r) {
                    consumerIds.add(Integer.valueOf(consumerId));
                }
            } else if (strategyRes.getStrategyObj() == 3) {
                for (String pkgId : r) {
                    pkgIds.add(Integer.valueOf(pkgId));
                }
            }
        }
        Map<Integer, Consumer> consumerMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(consumerIds)) {
            LambdaQueryWrapper<Consumer> consumerLambdaQueryWrapper = new LambdaQueryWrapper<>();
            consumerLambdaQueryWrapper.in(Consumer::getId, consumerIds)
                    .eq(Consumer::getSpId, spId)
                    .eq(Consumer::getIsDeleted, 0);
            List<Consumer> consumerList = consumerMapper.selectList(consumerLambdaQueryWrapper);
            if (!CollectionUtils.isEmpty(consumerList)) {
                consumerMap = consumerList.stream().collect(Collectors.toMap(Consumer::getId, Consumer -> Consumer, (a1, a2) -> a1));
            }
        }
        Map<Integer, ServicePkgRecord> pkgRecordMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(pkgIds)) {
            LambdaQueryWrapper<ServicePkgRecord> recordLambdaQueryWrapper = new LambdaQueryWrapper<>();
            recordLambdaQueryWrapper.in(ServicePkgRecord::getId, pkgIds)
                    .eq(ServicePkgRecord::getSpId, spId)
                    .eq(ServicePkgRecord::getIsDeleted, 0);
            List<ServicePkgRecord> pkgRecords = servicePkgRecordService.list(recordLambdaQueryWrapper);
            if (!CollectionUtils.isEmpty(pkgRecords)) {
                pkgRecordMap = pkgRecords.stream().collect(Collectors.toMap(ServicePkgRecord::getId, ServicePkgRecord -> ServicePkgRecord, (a1, a2) -> a1));
            }
        }
        for (RunningStrategyRes warn : warnList) {
            //根据客户id获取客户名称、行业名称
            String values = "";
            String strategyObjValues = warn.getStrategyObjValues();
            if (!StringUtils.isEmpty(strategyObjValues)
                    && strategyObjValues.contains(split)) {

                String[] r = strategyObjValues.split(WarnStrategyServiceImpl.split);
                if (r.length > 0) {
                    if (warn.getStrategyObj() == 1) {
                        if (!CollectionUtil.isEmpty(industryType)) {
                            for (String s : r) {
                                for (Map<String, String> map : industryType) {
                                    if (map.get("value").equals(s)) {
                                        values = map.get("alias") + "、" + values;
                                    }
                                }
                            }

                        }
                        //if (values.length() > 0) values = values.substring(0, values.length() - 1);
                    } else if (warn.getStrategyObj() == 2) {
//                        if (templateType != null && TemplateTypeEnum.TEMPLATE_TYPE_2.getCode() == templateType) {
//                            //按照客户选择
//                            values = consumerMapper.selectVccNames(spId, r);
//                        } else {
//                            //按照客户选择
//                            values = consumerMapper.selectNames(spId, r);
//                        }
                        if (templateType != null && TemplateTypeEnum.TEMPLATE_TYPE_2.getCode() == templateType) {
                            //按照客户选择
                            //values = consumerMapper.selectVccNames(spId, r);
                            for (String key : r) {
                                if (consumerMap.containsKey(Integer.valueOf(key))) {
                                    Consumer consumer = consumerMap.get(Integer.valueOf(key));
                                    values = values + consumer.getPhone() + "（" + consumer.getMemberId() + "）、";
                                }
                            }
                        } else {
                            //按照客户选择
                            //values = consumerMapper.selectNames(spId, r);
                            for (String key : r) {
                                if (consumerMap.containsKey(Integer.valueOf(key))) {
                                    Consumer consumer = consumerMap.get(Integer.valueOf(key));
                                    values = values + consumer.getCustName() + "（" + consumer.getSubsCode() + "）" + consumer.getName() +"、";
                                }
                            }
                        }
                    } else {
                        for (String key : r) {
                            if (pkgRecordMap.containsKey(Integer.valueOf(key))) {
                                values = values + pkgRecordMap.get(Integer.valueOf(key)).getPgkName() + "、";
                            }
                        }

                    }
                    if (values.length() > 0) values = values.substring(0, values.length() - 1);
                }
            }
            warn.setStrategyObjValues(values);
            if (warn.getStrategyObj()==0) warn.setStrategyObjValues("所有客户");
        }

    }

}
